package com.ag.oa.core.controller;

import com.ag.oa.core.entity.vo.SkillVO;
import com.ag.oa.core.entity.vo.UserVO;
import com.ag.oa.core.service.ISkillService;
import com.ag.oa.core.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by yxm on 14/10/2021.
 * 用户相关
 */
@RestController
@RequestMapping({"/user", "/test/user"})
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ISkillService skillService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 微信登录 auth.code2Session 获取用户唯一标识 OpenID 和 redis保存会话密钥 session_key
     */
    @RequestMapping(value = "/onLogin/code2Session", produces = "text/json;charset=UTF-8")
    public @ResponseBody String code2Session(String code) {

        JSONObject res = new JSONObject();
        try {
            userService.saveWxUserAuthRegister(code, res);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("success", false);
        }
        return res.toJSONString();
    }

    /**
     * 授权获取用户信息后 注册登录
     *
     * 小程序结合 wx.getUserProfile 使用，该授权方式，后续即将弃用 2022-11-22 wjc
     */
    @RequestMapping(value = "/authRegister", produces = "text/json;charset=UTF-8")
    public @ResponseBody String bindWeChat2Register(String openId, String userInfoStr) {

        JSONObject res = new JSONObject();
        int code = 200;

        logger.info("userInfo: "+ userInfoStr);
        try {
            userService.saveAuthRegisterUserInfo(openId, userInfoStr, res);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 完善老用户信息
     */
    @RequestMapping(value = "/completeUserInfo", produces = "text/json;charset=UTF-8")
    public @ResponseBody String completeUserInfo(String openId, String username, String phone, String smsCode) {

        JSONObject res = new JSONObject();
        res.put("resCode", 200);

        try {
            userService.saveCompleteUser(openId, username, phone, smsCode, res);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("resCode", 500);
        }

        return res.toJSONString();
    }

    /**
     * 新用户注册
     */
    @RequestMapping(value = "/newUserInfo", produces = "text/json;charset=UTF-8")
    public @ResponseBody String newUserInfo(String openId, String username, String phone, String smsCode) {

        JSONObject res = new JSONObject();
        res.put("resCode", 200);

        try {
            userService.saveNewUser(openId, username, phone, smsCode, res);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("resCode", 500);
        }

        return res.toJSONString();
    }


    @GetMapping("/isUserExists")
    @ResponseBody
    public String isUserExists(String phone){
        JSONObject res = new JSONObject();
        res.put("resCode", 200);

        try {
            int count = userService.getCountByPhone(phone);
            if (count == 1) {
                res.put("isExists", true);
            } else if (count == 0) {
                res.put("isExists", false);
            } else {
                res.put("resCode", 201);
                res.put("message", "数据异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.put("resCode", 500);
        }
        return res.toJSONString();
    }


    /**
     * 授权获取用户信息后保存更新
     */
    @RequestMapping(value = "/wx/auth/register", produces = "text/json;charset=UTF-8")
    public @ResponseBody String bindWeChat2Register(String openId, String encryptedStr, String ivStr
            , String sessionKey, String rawDataStr) {

        JSONObject res = new JSONObject();
        int code = 200;

        logger.info("openId: "+ openId +", encryptedStr: "+ encryptedStr +", ivStr: "+ ivStr
                +", sessionKey: "+ sessionKey +", rawDataStr: "+ rawDataStr);
        try {
            userService.updateAuthUserInfo(openId, encryptedStr, ivStr, sessionKey, rawDataStr, res);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 根据 id 获取用户信息
     */
    @RequestMapping(value = "/userInfo", produces = "text/json;charset=UTF-8")
    public @ResponseBody String getUserInfo(Integer userId, String openId) {

        JSONObject res = new JSONObject();
        int code = 201;

        try {
            UserVO user = userService.getUserInfoById(userId, openId);
            if (user!=null) {
                code = 200;

                res.put("isNewWXUser", false);
                res.put("userInfo", user);

                List<SkillVO> skillList = userService.getUserWorkSkillList(user.getId());
                res.put("skillList", skillList);
            } else {
                // 没有找到openId数据，表示属于小程序的新用户
                res.put("isNewWXUser", true);
            }
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 获取默认会员列表用户信息
     */
    @RequestMapping(value = "/pageUsers", produces = "text/json;charset=UTF-8")
    public @ResponseBody String getPageUserList(String username, Integer page, Integer pageSize) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            List<UserVO> dataArr = userService.getForPageList(null, username, page, pageSize);
            res.put("userArrList", dataArr);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 保存编辑用户信息
     */
    @RequestMapping(value = "/save/edit", produces = "text/json;charset=UTF-8")
    public @ResponseBody String saveModifyUser(Integer userId, String valueStr, Integer colType) {

        JSONObject res = new JSONObject();
        try {
            userService.updateModifyUserInfo(userId, valueStr, colType, res);
        }catch (Exception e) {
            e.printStackTrace();
            res.put("resCode", 500);
        }
        return res.toJSONString();
    }

    /**
     * 根据昵称查询获取用户 (忽略自己)
     */
    @RequestMapping(value = "/query/users", produces = "text/json;charset=UTF-8")
    public @ResponseBody String saveMyRefereeUser(Integer userId, String username) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            List<UserVO> userArrList = userService.queryUsersDataByUsername(userId, username);
            res.put("userArrList", userArrList);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 保存我的推荐人
     */
    @RequestMapping(value = "/referee/save", produces = "text/json;charset=UTF-8")
    public @ResponseBody String saveMyRefereeUser(Integer userId, Integer refereeUserId) {

        JSONObject res = new JSONObject();
        int code;

        try {
            code = userService.saveUpdateRefereeUser(userId, refereeUserId);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 保存我的推荐人
     */
    @RequestMapping(value = "/updateVipLevel")
    public String saveUserVip(Integer userId, Integer vipLevel) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            userService.updateUserVipLevel(userId, vipLevel);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    @RequestMapping(value = "/publicSwitchChange")
    public String publicSwitchChange(Integer userId, Boolean publicSwitchChecked){
        JSONObject res = new JSONObject();
        int code = 200;

        try {
            Integer publicStatus = publicSwitchChecked == true ? 1 : 0;
            userService.updatePublicStatusByUserId(userId, publicStatus);
        }catch (Exception e) {
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * ============================================ 工作技能相关 ============================================
     * 获取用户的所有工作技能信息
     */
    @RequestMapping(value = "/workSkills")
    public String getUserSkillData(Integer userId) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            List<SkillVO> skills = skillService.getUserAllWorkSkills(userId);
            res.put("skills", skills);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 根据 id 获取工作技信息
     */
    @RequestMapping(value = "/workSkillInfo")
    public String getWorkSkillData(Integer id) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            SkillVO skillVO = skillService.getWorkSkillInfoData(id);
            res.put("skillInfo", skillVO);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 保存添加或修改工作技能
     */
    @PostMapping("/workSkill/save")
    public String addOrUpdateUserWorkSkill(@RequestBody SkillVO skillVO) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            skillService.saveUserWorkSkill(skillVO);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * 根据 id 删除工作技能
     */
    @GetMapping("/delWorkSkill")
    public String delWorkSkill(Integer skillId) {

        JSONObject res = new JSONObject();
        int code = 200;

        try {
            skillService.delUserWorkSkill(skillId);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

    /**
     * ==================================== 任务相关 =====================================
     * 检查用户是否用添加任务的权限
     */
    @GetMapping("/checkAddTask")
    public String checkUserCanAddTask(Integer userId, Integer projectId) {

        JSONObject res = new JSONObject();
        int code = 200;
        boolean canIAdd = false;

        try {
            canIAdd = userService.getUserHasAuthAddTask(userId, projectId);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        res.put("canIAdd", canIAdd);
        return res.toJSONString();
    }

    /**
     * ==================================== 得分相关 =====================================
     * 用户积分得分相关
     */
    @GetMapping("/scoreRecords")
    public String getUserScoreRecords(Integer userId, Integer page, Integer pageSize) {

        JSONObject res = new JSONObject();
        int code = 200;
        try {
            List<Map<String, Object>> list = userService.getUserScoreRecordList(userId, page, pageSize);
            res.put("scoreArr", list);
        }catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        res.put("resCode", code);
        return res.toJSONString();
    }

}
